package com.ksd.utils.aes;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Arrays;
import java.util.Random;

/**
 * Description: AES128-CBC模式加密
 */
public class AESUtil{

	/**
	 * 256安全随机数（32位偏移量）
	 * @return
	 * @throws Exception
	 */
	public static String getRandomIVHexString() throws Exception
	{
		String base = "0123456789abcdef";
		Random random = new Random();
		StringBuffer code = new StringBuffer();
		for (int i = 0; i < 32; i++)
		{
			int number = random.nextInt(base.length());
			code.append(base.charAt(number));
		}
		return code.toString();
		/*logger.info("start getRandomIVHexString...");
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		logger.info("start getRandomIVHexString... 1");
		SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
		logger.info("start getRandomIVHexString... 2");
		sr.setSeed(SecureRandom.getInstance("SHA1PRNG").generateSeed(128));
		logger.info("start getRandomIVHexString... 3");
		kgen.init(128, sr); // 192 and 256 bits may not be available
		logger.info("start getRandomIVHexString... 4");
		SecretKey skey = kgen.generateKey();
		logger.info("start getRandomIVHexString... 5");
		byte[] raw = skey.getEncoded();
		logger.info("start getRandomIVHexString... 6");
		return toHex(raw);// 十六进制表示
*/	}

	/**
	 * 描述：加密接口（32位偏移量）获得一个64位密文
	 *
	 * @param sSrc
	 *            ：加密字符串
	 * @param sKey
	 *            ：密钥
	 * @param sIv
	 *            加密字符偏移量
	 * @return：密文，十六进制表示
	 * @throws Exception
	 */
	public static String encrypt(String sSrc, String sKey,
			String sIv) throws Exception
	{
		byte[] srcByte = sSrc.getBytes();
		byte[] ivByte = toByte(sIv);
		byte[] result = encrypt(sKey, srcByte, ivByte);
		return toHex(result);// 转化为十六进制传输
	}

	// android自带的加密流程
	private static byte[] encrypt(String sKey, byte[] srcByte, byte[] ivByte)
			throws Exception
	{
		SecretKeySpec skeySpec = getKey(sKey);
		Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(ivByte));
		byte[] encrypted = cipher.doFinal(srcByte);
		return encrypted;
	}

	private static SecretKeySpec getKey(String sKey)
			throws UnsupportedEncodingException
	{
		int keyLength = 128;
		byte[] keyBytes = new byte[keyLength / 8];
		Arrays.fill(keyBytes, (byte) 0x0);
		byte[] sKeyBytes = sKey.getBytes();
		int length = sKeyBytes.length < keyBytes.length ?sKeyBytes.length
				: keyBytes.length;
		System.arraycopy(sKeyBytes, 0, keyBytes, 0, length);
		SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");
		return key;
	}

	private static byte[] toByte(String hexString)
	{
		int len = hexString.length() / 2;
		byte[] result = new byte[len];
		for (int i = 0; i < len; i++)
		{
			result[i] = Integer.valueOf(hexString.substring(2 * i, 2 * i + 2),
					16).byteValue();
		}
		return result;
	}

	private static String toHex(byte[] buf)
	{
		if (buf == null)
		{
			return "";
		}
		StringBuffer result = new StringBuffer(2 * buf.length);
		for (int i = 0; i < buf.length; i++)
		{
			appendHex(result, buf[i]);
		}
		return result.toString();
	}

	private static void appendHex(StringBuffer result, int b)
	{
		if (b < 0)
		{
			b += 256;
		}
		if (b < 16)
		{
			result.append("0");
		}
		result.append(Integer.toHexString(b));
	}
}
